package com.jiujiu.utitls;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import sun.rmi.runtime.Log;

import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @author ZhaoJunZhou
 * @Date 2020/11/4
 */
public class CreateMarker {
    private static final Logger LOG = Logger.getLogger(CreateMarker.class);
    private Configuration configuration;
    private File from;
    private String to;
    private Template template;
    private Map<String, Object> _commonMap;
    {
        configuration = new Configuration(Configuration.VERSION_2_3_22);
        configuration.setDefaultEncoding("UTF-8");
    }

    public CreateMarker(JSONObject jsonObject) {
        Preconditions.checkArgument(jsonObject.containsKey("from"),"未找到关键词，from");
        Preconditions.checkArgument(jsonObject.containsKey("to"),"未找到关键词，to");
        from= MyFiles.getFile(jsonObject.get("from").toString());
        to = jsonObject.get("to").toString();

    }
    public CreateMarker(File _from, String  _to)  {
        from = _from;
        to = _to;
        String fileName = from.getName();
        Preconditions.checkArgument(StringUtils.contains(fileName, "ftl"), "文件需要以ftl结尾,"+fileName);

    }
    public boolean createFile(){
        return createFile(null);
    }

    /**
     * 根据传入的data数据开始进行freemarker的生成
     * 同时在这里会把基础的{@link ContentMap#getExpandParameter()} 生成的
     * map混入到其中，如果传入的和基础的名字冲突会以传入的为主
     * @param data 传入的data
     * @return
     */
    public boolean createFile(Map<String,Object> data) {
        try {

            _commonMap = ContentMap.getExpandParameter();
            _commonMap.putAll(data);
            configuration.setDirectoryForTemplateLoading(from.getParentFile());
            template = configuration.getTemplate(from.getName());
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to)));
            LOG.info(String.format("传入freemarker的参数为:%s", _commonMap.toString()));
            template.process(data, out);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
